import asyncio
import random

import pygame

import cfg
from debug import debug
from units.uiUtil import playMyBgMusic, gameBgImg

bg = pygame.image.load('assets/image/bg.png')

musicGold = pygame.mixer.Sound('bricks/music/m1.mp3')
# 定义砖块宽高
brickWidth, brickHeight = 80, 20
# 砖块行列
brickRows, brickCols = 3, 7
# 定义砖块数组
bricks = []
# 定义木板
plank = {'rect':pygame.Rect(0, 1000, 80, 10),'color':'black'}

class MainBricks:
    def __init__(self, dims, FPS=60):
        self.dims = dims
        self.FPS = FPS
        # 游戏运行控制变量（gamen_running）
        self.game_running = True
        self.score = 0
        self.plankMoveDirection = "stop"
        self.ball_x, self.ball_y = dims[0]/2, 989
        self.ballMove_x, self.ballMove_y = 0, 0

    # 游戏主循环所在函数需要由 async 定义
    async def start(self):
        # 初始化游戏界面（screen）：尺寸、背景色等
        screen = pygame.display.set_mode(self.dims)
        # 显示游戏名称
        pygame.display.set_caption("打砖块")
        # 初始化游戏时钟（clock），由于控制游戏帧率
        clock = pygame.time.Clock()
        # 播放背景音乐
        # playMyBgMusic('')

        # 初始化砖块数组
        for x in range(brickRows):
            bricks.append([])
            for y in range(brickCols):
                bricks[x].append(1)

        # 初始化小球运动速度
        self.ballMove_x = random.randint(1, 4)
        self.ballMove_y = -8
        # 游戏主循环
        while cfg.inGame:
            # 按照给定的 FPS 刷新游戏
            # clock.tick() 函数返回上一次调用该函数后经历的时间，单位为毫秒 ms
            # dt 记录上一帧接受之后经历的时间，单位为秒 m
            # 使用 dt 控制物体运动可以使游戏物理过程与帧率无关
            dt = clock.tick(self.FPS) / 1000.0
            # 使用 asyncio 同步
            # 此外游戏主体代码中不需要再考虑 asyncio
            await asyncio.sleep(0)

            # 游戏事件处理
            # 包括键盘、鼠标输入等
            for event in pygame.event.get():
                # 点击关闭窗口按钮或关闭网页
                if event.type == pygame.QUIT:
                    pygame.quit()
                # 当 game_running 为 False 时，
                # 让木板跟随键盘移动
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        self.plankMoveDirection = "left"
                        # plank["rect"].x -= 10 if plank["rect"].x > 10 else plank["rect"].x
                    if event.key == pygame.K_RIGHT:
                        self.plankMoveDirection = "right"
                        # plank["rect"].x += 10 if plank["rect"].x < self.dims[1] else plank["rect"].x
                if event.type == pygame.MOUSEMOTION:
                    self.plankMoveDirection = "stop"
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    if mouse_x<self.dims[0]-80:
                        plank["rect"].x = mouse_x
                    else:
                        plank["rect"].x = self.dims[0]-80

            # 以背景色覆盖刷新游戏界面
            gameBgImg(screen, bg, 270, self.dims)

            # 调用 debug 函数在游戏界面左上角显示游戏帧率
            debug(f"{clock.get_fps():.1f}", color='green')

            # 画砖块
            for row in range(brickRows):
                for col in range(brickCols):
                    if bricks[row][col] == 1:
                        pygame.draw.rect(screen, "black",((20+(20+brickWidth)*col), (200+(10+brickHeight)*row), brickWidth, brickHeight ))

            # 挡板运动
            if self.plankMoveDirection == "left":
                plank['rect'].x -= 8
                if plank['rect'].x < 0:
                    plank['rect'].x = 0
            if self.plankMoveDirection == "right":
                plank['rect'].x += 8
                if plank['rect'].x > self.dims[0] - plank['rect'].width:
                    plank['rect'].x = self.dims[0] - plank['rect'].width

            # 绘制木板
            pygame.draw.rect(screen, plank['color'],plank['rect'])

            # 小球运动
            self.ball_x += self.ballMove_x
            self.ball_y += self.ballMove_y
            # 检测球与挡板碰撞
            if (self.ball_x + 10 >= plank['rect'].x and
                    self.ball_x - 10 <= plank['rect'].x + 80 and
                    self.ball_y + 10 >= plank['rect'].y and
                    self.ball_y - 10 <= plank['rect'].y + 80):
                self.ballMove_y = - self.ballMove_y
                self.ball_y += self.ballMove_y
                musicGold.play()
                self.ballMove_x += random.randint(-3, 3)
                self.ball_x += self.ballMove_x

            # 判断小球低于木板，游戏结束
            if self.ball_y > 1010:
                self.game_running = False
            # 检测球与砖块碰撞
            for row in range(brickRows):
                for col in range(brickCols):
                    if bricks[row][col] == 1:
                        if (self.ball_x+10 >= (20+(20+brickWidth)*col) and
                        self.ball_x-10 <= (20+(20+brickWidth)*col)+80 and
                        self.ball_y+10 >= (200+(10+brickHeight)*row) and
                        self.ball_y-10 <= (200+(10+brickHeight)*row)+20):
                            bricks[row][col] = 0
                            musicGold.play()
                            self.ballMove_y = - self.ballMove_y
                            self.ball_y += self.ballMove_y
                            # self.ballMove_x = -self.ballMove_x
                            self.ball_x += self.ballMove_x

            # 检测球运动出屏幕
            if self.ball_x+10 > self.dims[0] or self.ball_x-10 < 0:
                self.ballMove_x = -self.ballMove_x
                self.ball_x += self.ballMove_x
            if self.ball_y+10 < 200:
                self.ballMove_y = -self.ballMove_y
                self.ball_y += self.ballMove_y
            # 画小球
            pygame.draw.circle(screen, "black", (self.ball_x, self.ball_y), 10, 0)

            # 将游戏界面内容输出至屏幕
            pygame.display.update()

        # 跳出游戏主循环，退出游戏
        cfg.inGame = False